<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/9/28
 * Time: 19:45
 */

class Express extends CS_Controller
{
    public function _init()
    {
        $this->load->library('pagination');
        $this->load->model('express_model', 'express');
    }

    public function index($pg = 1)
    {
        $page_num = 20;
        $num = ($pg-1)*$page_num;
        $config['first_url'] = base_url('express/index').$this->pageGetParam($this->input->get());
        $config['suffix'] = $this->pageGetParam($this->input->get());
        $config['base_url'] = base_url('express/index');
        $config['total_rows'] = $this->express->total($this->input->get());
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['pg_list'] = $this->express->page_list($page_num, $num, $this->input->get());
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $this->load->view('express/index', $data);
    }

    public function add()
    {
        $this->load->view('express/add');
    }

    public function addPost()
    {
    	$result = $this->express->isExist($this->input->post('name'), $this->input->post('company'));
        if($result->num_rows() > 0){
            $this->error('express/add', '', '快递已存在，不要在添加啦`~`');
        }
    	
        $resultId = $this->express->insert($this->input->post());
        if ($resultId) {
            $this->success('express/index', '', '添加成功！');
        } else {
            $this->error('express/add', '', '添加失败！');
        }
    }

    public function edit($id)
    {
        $result = $this->express->findById($id);
        if($result->num_rows() <= 0){
            $this->error('express/index', '', '快递编号不存在！');
        }
        $data['express'] = $result->row();
        $this->load->view('express/edit', $data);
    }

    public function editPost()
    {
    	$result = $this->express->isExist($this->input->post('name'), $this->input->post('company'));
        if($result->num_rows() > 0){
            if($result->num_rows() > 1) {
                $this->error('express/edit/'.$this->input->post('id'), '', '放弃吧，快递已存在啦`.`!');
            }
            $result = $result->row();
            if($result->id != $this->input->post('id')){
                $this->error('express/edit/'.$this->input->post('id'), '', '放弃吧，快递已存在啦`.`!');
            }
        }
    	
        $resultId = $this->express->update($this->input->post());
        if ($resultId) {
            $this->success('express/index', '', '更新成功！');
        } else {
            $this->error('express/edit/'.$this->input->post('id'), '', '更新失败！');
        }
    }

    public function delete($id)
    {
        $resultId = $this->express->delete($id);
        if ($resultId) {
            $this->success('express/index', '', '删除成功！');
        } else {
            $this->error('express/index', '', '删除失败！');
        }
    }
}